<template>
  <a-card :bordered="false" :style="CardStyle">
    <div v-show="showserch" :style="SearchStyle" class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-form-item>
          <div class="title">
            <p class="searchTitle"><span>客户检索</span></p>
          </div>
          <div class="ClientFa">
            <a-input
              v-model="keyword"
              :allowClear="true"
              class="Client"
              placeholder="客户名称/编号"
              @keydown="inputKeyDown"
            >
              <a-button
                slot="suffix"
                class="search-btn"
                size="large"
                style="margin: 0 -12px 0 12px"
                type="primary"
                @click="Retrieval">
                <a-icon type="search"/>
                检索
              </a-button>
            </a-input>
          </div>
        </a-form-item>
      </a-form>
    </div>
    <div v-show="!showserch" class="table-page-search-wrapper">
      <a-row :gutter="10">
        <a-col :span="6"></a-col>
        <a-col :span="12">
          <a-input v-model="keyword" :allowClear="true" class="Client" @keydown="inputKeyDown">
            <a-button
              slot="suffix"
              class="search-btn"
              size="large"
              style="margin: 0 -12px 0 12px"
              type="primary"
              @click="Retrieval">
              <a-icon type="search"/>
              检索
            </a-button>
          </a-input>
          <span style="color: #bfbfbf">请输入要检索的关键字信息：客户名称/编号&nbsp;(省市区名称禁止查询)</span>
        </a-col>
        <a-col :span="6">
          <a-button v-if="data.length <= 0" size="large" style="margin-right: -12px" type="primary" @click="addGetList">
            备案
          </a-button>
        </a-col>
      </a-row>
    </div>
    <a-table
      v-show="!showserch"
      ref="table"
      :bordered="true"
      :columns="columns"
      :dataSource="data"
      :loading="loading"
      :rowKey="(row, index) => row.Id"
      :scroll="{ y: tableHeight }"
      size="small"
      style="margin-top: 20px">
      <template slot="cCusType" slot-scope="text, record">
        <a-tag v-if="record.cCusType === -1">备案中</a-tag>
        <a-tag v-else-if="record.cCusType === 0" color="blue">潜在</a-tag>
        <a-tag v-else-if="record.cCusType === 1" color="green">正式</a-tag>
        <a-tag v-else-if="record.cCusType === 2" color="red">休眠</a-tag>
        <a-tag v-else-if="record.cCusType === 3" color="orange">待转正</a-tag>
      </template>
      <template slot="GroupName" slot-scope="text, record">
        <a-tag v-if="record.GroupStatus == 0" color="red">未分组</a-tag>
        <a-tag v-else-if="record.GroupStatus == 1" color="cyan">申请中</a-tag>
        <a-tag v-else color="green">{{ record.GroupName }}</a-tag>
      </template>
      <template slot="dataindex" slot-scope="text, record, index">
        {{ (1 - 1) * 10 + index + 1 }}
      </template>
      <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span>
      <template slot="action" slot-scope="text, record">
        <a v-if="hasPerm('Cust_CustomerRetrieval.details')" @click="handleRevise(record)">详情</a>
        <a-divider v-if="hasPerm('Cust_CustomerRetrieval.details') && record.GroupStatus == 0" type="vertical"/>
        <a v-if="hasPerm('Cust_CustomerRetrieval.apply') && record.GroupStatus == 0" @click="handleApply(record)">申请</a>
        <a-divider v-if="record.cCusType == -1 || record.cCusType == 0" type="vertical"/>
        <a v-if="record.cCusType == -1 || record.cCusType == 0" @click="dele(record.Id)">删除</a>
      </template>
    </a-table>
    <a-modal
      :confirm-loading="modalLoading"
      :visible="show"
      title="客户申请"
      width="30%"
      @cancel="resetSelectGroup"
      @ok="sub">
      <a-select v-model="entity.GroupId" placeholder="请选择分组" style="width: 100%">
        <a-select-option v-for="item in groupList" :key="item.GroupId" :value="item.GroupId">{{ item.GroupName }}
        </a-select-option>
      </a-select>
    </a-modal>
    <CusEditForm ref="details" :parentObj="this"></CusEditForm>
    <Detailsfrom ref="detailsfrom" :parentObj="this"></Detailsfrom>
  </a-card>
</template>

<script>
import OperatorCache from '@/utils/cache/OperatorCache'
// 客户分配
import CusEditForm from '@/views/CustomerManagement/Customer/EditForm.vue'
import Detailsfrom from '@/views/CustomerManagement/Customer/Details.vue'

import moment from 'moment'

const columns = [
  { title: '序号', dataIndex: 'dataindex', align: 'center', width: '50px', scopedSlots: { customRender: 'dataindex' } },
  { title: '客户编码', dataIndex: 'cCusCode', align: 'center', width: '100px' },
  { title: '客户名称', dataIndex: 'cCusName', align: 'left', width: '270px' },
  { title: '备案人', dataIndex: 'RealName', align: 'center', width: '80px' },
  { title: '备案时间', dataIndex: 'CreateTime', align: 'center', width: '100px', scopedSlots: { customRender: 'CreateTime' } },
  { title: '客户类型', dataIndex: 'cCusType', align: 'center', width: '50px', scopedSlots: { customRender: 'cCusType' } },
  { title: '客户分组', dataIndex: 'GroupName', align: 'center', width: '80px', scopedSlots: { customRender: 'GroupName' } },
  { title: '操作', dataIndex: 'action', align: 'left', scopedSlots: { customRender: 'action' }, width: '80px' }
]

export default {
  components: {
    CusEditForm,
    OperatorCache,
    Detailsfrom
  },
  activated () {
    this.data = []
    this.keyword = ''
    this.showserch = true
    this.getGroupList()
  },
  data () {
    return {
      cardHeight: 780, // card 高度
      tableHeight: 558, // 表格高度
      flagBL: false,
      show: false,
      modalLoading: false,
      showserch: true,
      IsFormal: true,
      keyword: '',
      data: [],
      dataArr: [],
      list: [], // 省级
      listChildren: [], // 市
      county: [], // 县
      filters: {},
      sorter: { field: 'cCusCode', order: 'desc' },
      queryParam: [],
      loading: false,
      columns,
      selectedRowKeys: [],
      selectedRows: [],
      entity: {},
      groupList: []
    }
  },
  mounted () {
    this.$nextTick(() => {
      // 页面渲染完成后的回调
      this.cardHeight = this.getTableHeight(false) - 108
    })
  },
  watch: {
    showserch (value) {
      if (value === false) {
        this.$nextTick(() => {
          // 页面渲染完成后的回调
          this.tableHeight = this.getTableHeight(true) + 24.5
        })
      }
    }
  },
  computed: {
    CardStyle () {
      return {
        minHeight: this.cardHeight + 'px'
      }
    },
    SearchStyle () {
      return {
        marginTop: (this.cardHeight / 15) + 'px'
      }
    }
  },
  methods: {
    dele (ids) {
      const thisObj = this
      this.$confirm({
        title: '客户信息删除会解除与分组关系,确定删除吗?',
        onOk () {
          return new Promise((resolve, reject) => {
            thisObj.$http
              .post('/CustomerManagement/CustomerInfo/DeleteDataByCustomerId', { id: ids })
              .then((resJson) => {
                resolve()

                if (resJson.Success) {
                  thisObj.$message.success('操作成功!')

                  thisObj.getDataList()
                } else {
                  thisObj.$message.error(resJson.Msg)
                }
              })
          })
        }
      })
    },
    // 客户备案
    addGetList () {
      this.$refs.detailsfrom.openForm(null, '客户备案')
    },
    getGroupList () {
      this.$http
        .post('/CustomerManagement/Cust_GroupAllocationOfUser/GetDataList', {
          Search: {
            Condition: 'SalesmanId',
            Keyword: this.op().Id
          }
        })
        .then((res) => {
          this.groupList = res.Data
        })
    },
    sub () {
      if (!this.entity.GroupId) return this.$message.error('请选择分组')
      const thisObj = this
      this.$confirm({
        title: '确认提交客户申请吗?',
        onOk () {
          return new Promise((resolve, reject) => {
            thisObj.$http.post('/CustomerManagement/Cust_CustomerApply/SaveData', thisObj.entity).then((resJson) => {
              resolve()
              if (resJson.Success) {
                thisObj.$message.success('客户申请提交成功!')
                thisObj.resetSelectGroup()
                thisObj.getDataList()
              } else {
                thisObj.$message.error(resJson.Msg)
              }
            })
          })
        }
      })
    },
    resetSelectGroup () {
      this.show = false
      this.entity.GroupId = undefined
    },
    op () {
      return OperatorCache.info
    },
    Retrieval () {
      if (!this.keyword || this.keyword.length < 2) return this.$message.error('查询内容不能小于两个字')
      this.loading = true
      this.getDataList(true)
    },
    inputKeyDown (e) {
      if (e.keyCode === 13) {
        if (!this.keyword || this.keyword.length < 2) return this.$message.error('查询内容不能小于两个字')
        this.loading = true
        this.getDataList(true)
      }
    },
    handleApply (row) {
      this.entity.CustomerId = row.Id
      this.entity.CustomerName = row.cCusName
      this.entity.SalesmanId = this.op().Id
      this.entity.SalesmanName = this.op().RealName
      this.entity.ApplyDate = new Date()
      this.entity.ApprovalStatus = 0
      this.entity.Type = '2'
      this.show = true
    },
    getDataList (flag) {
      this.selectedRowKeys = []
      this.loading = true
      this.$http
        .post('/CustomerManagement/CustomerInfo/GetDataListForCustomerInfoRetrieval', {
          PageIndex: 1,
          PageRows: 10,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          Search: { cCusName: this.keyword, cCusType: null, isAllData: true },
          ...this.filters
        })
        .then((resJson) => {
          this.loading = false
          if (resJson.Success) {
            this.data = resJson.Data
            if (flag && this.showserch) {
              this.showserch = false
            }
          } else {
            this.$message.error(resJson.Msg)
          }
        })
    },
    handleRevise (row) {
      this.$http.post('/CustomerManagement/CustomerInfo/GetIsMyCustomerByOperator?CustomerId=' + row.Id).then((res) => {
        if (res.Success) {
          if (res.Data) {
            this.$refs.details.openForm(row, '详情', res.Data, false)
          } else {
            this.$refs.details.openForm(row, '详情', res.Data, true)
          }
        }
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    hasSelected () {
      return this.selectedRowKeys.length > 0
    },
    timeFormat (val) {
      // 时间格式化函数
      return moment(val).format('YYYY-MM-DD HH:mm:ss')
    }
  }
}
</script>

<style lang="less">
.Client {
  height: 40px;
}

.ClientFa {
  margin: 40px auto;
  width: 40%;
}

.title .searchTitle {
  margin: 160px 0 50px;
  text-align: center;
  letter-spacing: 30px;
  font-size: 55px;
  font-family: 幼圆, serif;
  font-weight: bold;
  color: #8d8d8d;
}
</style>
